<template>
  <div>
    <my-breadcrumb :items="['资讯管理', '资讯列表']"/>
    <search :formItems="searchItems" :check="true" @search="getList" ref="search"/>
    <div class="add">
      <el-button type="primary" @click="toAdd">新增资讯</el-button>
      <el-button type="primary" @click="toExport" :loading="loading">导出资讯</el-button>
      <div style="display: inline-block;" v-show="selection.length">
        <el-button type="primary" @click="review(1)">批量审核通过</el-button>
        <el-button type="primary" @click="review(3)">批量驳回</el-button>
      </div>
    </div>
    <el-table :data="news" border @sort-change="orderByTime" @select="selectChange" @select-all="selectChange" style="width: 100%;">
      <el-table-column
        type="index"
        width="55">
      </el-table-column>
      <el-table-column
        type="selection"
        :selectable="selectable"
        width="55">
      </el-table-column>
      <el-table-column
        label="ID"
        prop="id">
      </el-table-column>
      <el-table-column
        label="创建时间"
        width="100px"
        align="center"
        sortable="custom"
        prop="createtime">
      </el-table-column>
      <el-table-column
        label="商家"
        width="140px"
        prop="membername">
      </el-table-column>
      <el-table-column
        label="资讯类型"
        prop="typeid">
        <template slot-scope="scope">
          {{ newsType[scope.row.typeid - 1] ? newsType[scope.row.typeid - 1].name : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="标题"
        width="150px"
        prop="title">
      </el-table-column>
      <el-table-column
        label="商品名称"
        prop="name">
      </el-table-column>
      <el-table-column
        label="审核状态"
        prop="auditstatus">
        <template slot-scope="scope">
          <!--1-审核通过 2-审核中 3-驳回 4-保存-->
          {{ scope.row.auditstatus === '1' ? '审核通过' : (scope.row.auditstatus === '2' ? '审核中' : (scope.row.auditstatus === '3' ? '驳回' : '保存'))}}
        </template>
      </el-table-column>
      <el-table-column
        label="删除原因"
        prop="delcontent">
      </el-table-column>
      <el-table-column
        label="阅读量"
        sortable="custom"
        width="90px"
        prop="clickcount">
      </el-table-column>
      <el-table-column
        label="评论量"
        width="90px"
        sortable="custom"
        prop="commentcount">
      </el-table-column>
      <el-table-column
        label="点赞量"
        width="90px"
        sortable="custom"
        prop="fabulous">
      </el-table-column>
      <el-table-column
        label="收藏量"
        width="90px"
        sortable="custom"
        prop="collcount">
      </el-table-column>
      <el-table-column
        label="品牌分类"
        prop="brandid">
        <template slot-scope="scope">
          {{ brand[scope.row.brandid - 1] ? brand[scope.row.brandid - 1].name : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="风格分类"
        prop="styleid">
        <template slot-scope="scope">
          {{ style[scope.row.styleid - 1] ? style[scope.row.styleid - 1].name : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="服装类型"
        width="180px"
        prop="clothingid">
        <template slot-scope="scope">
          <el-tag v-for="(t, i) in scope.row.clothingid" :key="i" v-if="clothing[t - 1]" style="margin-right: 4px;">{{ clothing[t - 1].name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        width="100px"
        align="center"
        sortable="custom"
        prop="strattime">
      </el-table-column>
      <el-table-column
        label="结束时间"
        width="100px"
        sortable="custom"
        align="center"
        prop="endtime">
        <template slot-scope="scope">
          {{ scope.row.endtime ? scope.row.endtime : '售完下架' }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否置顶"
        sortable="custom"
        width="110px"
        prop="istop">
        <template slot-scope="scope">
          {{ scope.row.istop === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        label="是否热门"
        prop="sourcetype">
        <template slot-scope="scope">
          {{ scope.row.sourcetype === '1' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180px"
        align="center"
        fixed="right"
        prop="id">
        <template slot-scope="scope">
          <div v-if="scope.row.auditstatus === '1'" style="display: inline-block;">
            <el-button size="mini" type="text" @click="toGetComment(scope.row.id)" :disabled="scope.row.delflag === '1'">查看评论</el-button>
          </div>
          <div v-if="scope.row.auditstatus === '2' && scope.row.delflag !== '1'" style="display: inline-block;">
            <el-button type="text" @click="toPass(scope.row, 1)">审核通过</el-button>
            <el-button type="text" @click="toPass(scope.row, 0)">驳回</el-button>
          </div>
          <el-button size="mini" type="text" @click="toUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.delflag === '0'" size="mini" type="text" @click="toDelete(scope.row.id, scope.row.memberid)">删除</el-button>
          <el-button v-else type="text" disabled>已删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    <el-dialog title="资讯详情" :visible.sync="showDetail" width="760px" :close-on-click-modal="false">
      <el-form ref="addForm" :rules="rules" :model="detailRow" inline label-width="90px" class="form">
        <el-form-item label="ID" prop="id">
          <el-input v-model="detailRow.id" disabled style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="资讯类型" prop="typeid">
          <el-radio-group v-model="detailRow.typeid">
            <el-radio label="1">上新</el-radio>
            <el-radio label="2">图透</el-radio>
            <el-radio label="3">尾款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="detailRow.name" :disabled="detailRow.typeid !== '2'" style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="服装类型" prop="clothingid">
          <el-select :disabled="detailRow.typeid !== '2'" multiple v-model="detailRow.clothingid">
            <el-option v-for="(item, index) in clothing" :key="index" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="风格分类" prop="styleid">
          <el-select v-model="detailRow.styleid" :disabled="detailRow.typeid !== '2'">
            <el-option v-for="(item, index) in style" :key="index" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌分类" prop="brandid">
          <el-select v-model="detailRow.brandid" :disabled="detailRow.typeid !== '2'">
            <el-option value="1" label="日牌"/>
            <el-option value="2" label="国牌"/>
            <el-option value="3" label="其他"/>
          </el-select>
        </el-form-item>
        <el-form-item label="选择裙子" prop="skirtid" style="width: 100%;" v-if="detailRow.typeid !== '2'">
          <div class="select-box">
            <img :src="nowSkirt.img1" alt="" width="40" v-if="nowSkirt.img1">
            <span v-if="nowSkirt.name">{{ nowSkirt.name }}</span>
            <el-button type="text" @click="toSelectSkirt">点击选择裙子</el-button>
          </div>
        </el-form-item>
        <el-form-item label="选择商家" prop="memberid" style="width: 100%;" v-if="detailRow.typeid === '2'">
          <div class="select-box">
            <span v-if="nowMember.name">{{ nowMember.name }}</span>
            <el-button type="text" @click="toSelectMember">点击选择商家</el-button>
          </div>
        </el-form-item>
        <el-form-item label="淘口令" prop="tbtoken" style="width: 100%;">
          <el-input v-model="detailRow.tbtoken" style="width: 500px;" :autosize="{minRow: 3, maxRow: 6}" type="textarea"/>
        </el-form-item>
        <el-form-item label="上架时间" prop="strattime" v-if="detailRow.typeid !== '2'">
          <el-date-picker
            v-model="detailRow.strattime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="上架时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下架时间" prop="endtime" v-if="detailRow.typeid !== '2'">
          <el-date-picker
            v-model="detailRow.endtime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="下架时间(售完下架无需选择)">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="detailRow.title"/>
        </el-form-item>
        <el-form-item label="图片" prop="imgarr" style="width: 100%;">
          <!-- 图片列表 -->
          <div class="img-box" v-for="(image, index) in imageArr" :key="index">
            <img :src="image" class="avatar">
            <i class="el-icon-close" @click="delImage(index)"></i>
          </div>
          <el-upload
            class="avatar-uploader"
            action="#"
            v-if="imageArr.length < 6"
            :show-file-list="false"
            :before-upload="beforeUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="点赞量" prop="fabulous">
          <el-input v-model="detailRow.fabulous"/>
        </el-form-item>
        <el-form-item label="收藏量" prop="collcount">
          <el-input v-model="detailRow.collcount"/>
        </el-form-item>
        <el-form-item label="阅读量" prop="clickcount">
          <el-input v-model="detailRow.clickcount"/>
        </el-form-item>
        <el-form-item label="资讯详情" prop="content" style="width: 100%;">
          <el-input v-model="detailRow.content" type="textarea" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="不通过原因" prop="rejectcontent" label-width="85px" v-show="detailRow.auditstatus === '3'">
          <el-input type="textarea" v-model="detailRow.rejectcontent" style="width: 500px"/>
        </el-form-item>
        <el-form-item label="是否置顶" prop="istop">
          <el-select v-model="detailRow.istop">
            <el-option value="0" label="否"/>
            <el-option value="1" label="是"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否热门" prop="sourcetype">
          <el-select v-model="detailRow.sourcetype">
            <el-option value="0" label="否"/>
            <el-option value="1" label="是"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="footer" v-if="showFooter">
        <el-button type="primary" @click="toSub(2)">提交审核</el-button>
        <el-button type="primary" @click="toSub(4)">保存</el-button>
        <el-button type="error" @click="showDetail = false">取消</el-button>
      </div>
      <div class="footer" slot="footer" v-else>
        <el-button type="primary" @click="toSub">提交</el-button>
        <el-button type="error" @click="showDetail = false">取消</el-button>
      </div>
    </el-dialog>
    <comment ref="comment"/>
    <select-list ref="selectList" :url="'/Skirti/index?status=0&delflag=0'" :searchItems="skirtSearch" :tableItem="skirtTableItems" @selectRow="skirtChange"/>
    <select-list ref="selectMember" :url="'business/index?placardstatus=1&delflag=0'" :searchItems="businessSearch" :tableItem="businessTableItems" @selectRow="memberChange"/>
  </div>
</template>

<script>
import CLAZZ from '@/config/classify'
import tableItems from '@/config/tableItems'
import {toExport, deletePrompt} from '@/utils/getList'
import comment from '@/components/common/comment'
import selectList from '@/components/common/selectList'
export default {
  name: 'index',
  data () {
    return {
      searchItems: [
        {
          label: '资讯类型',
          type: 'select',
          key: 'typeid',
          options: CLAZZ.news
        },
        {
          label: '标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '商品名称',
          type: 'input',
          key: 'name'
        },
        {
          label: '服装类型',
          type: 'select',
          key: 'clothingid',
          options: CLAZZ.clothing
        },
        {
          label: '风格分类',
          type: 'select',
          key: 'styleid',
          options: CLAZZ.style
        },
        {
          label: '品牌分类',
          type: 'select',
          key: 'brandid',
          options: CLAZZ.brand
        },
        {
          label: '发布时间',
          type: 'times',
          key: 'times'
        },
        {
          label: '商家名称',
          type: 'input',
          key: 'businessname'
        },
        {
          label: '审核状态',
          type: 'select',
          key: 'auditstatus',
          options: [{id: '1', name: '审核通过'}, {id: '2', name: '审核中'}, {id: '3', name: '驳回'}] // , {id: '4', name: '保存'}
        },
        {
          label: '是否置顶',
          type: 'select',
          key: 'istop',
          options: [{id: '0', name: '否'}, {id: '1', name: '是'}]
        },
        {
          label: '是否热门',
          type: 'select',
          key: 'sourcetype',
          options: [{id: '0', name: '否'}, {id: '1', name: '是'}]
        }
      ], // 检索结构
      skirtSearch: [
        {
          label: '裙子名称',
          type: 'input',
          key: 'skirtname'
        },
        {
          label: '商家名称',
          type: 'input',
          key: 'businessname'
        }
      ], // 检索结构
      businessSearch: [
        {
          label: '商家名称',
          type: 'input',
          key: 'name'
        },
        {
          label: '服装范围',
          type: 'selects',
          key: 'managementid',
          options: CLAZZ.managementid
        },
        {
          label: '等级',
          type: 'select',
          key: 'level',
          options: CLAZZ.level
        }
      ],
      skirtTableItems: tableItems.skirtList, // 选择裙子表格结构
      businessTableItems: tableItems.memberList,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      news: [],
      showDetail: false,
      detailRow: {
        id: '',
        typeid: '',
        name: '',
        clothingid: [],
        imgarr: [],
        styleid: '',
        brandid: '',
        skirtid: '',
        tbtoken: '',
        strattime: '',
        endtime: '',
        title: '',
        fabulous: '',
        collcount: '',
        clickcount: '',
        content: '',
        // auditstatus: '',
        // rejectcontent: '',
        istop: '',
        sourcetype: '',
        memberid: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入资讯标题', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入资讯内容', trigger: 'blur' }
        ],
        styleid: [
          { required: true, message: '请选择风格类型', trigger: 'change' }
        ],
        typeid: [
          { required: true, message: '请选择资讯类型', trigger: 'change' }
        ],
        strattime: [
          { required: true, message: '请选择上架时间', trigger: 'change' }
        ],
        memberid: [
          { required: true, message: '请选择商家', trigger: 'change' }
        ],
        skirtid: [
          { required: true, message: '请选择裙子', trigger: 'change' }
        ],
        clothingid: [
          { required: true, message: '请选择服装分类', trigger: 'change' }
        ],
        imgarr: [
          { required: true, message: '请选择图片', trigger: 'change' }
        ],
        auditstatus: [
          { required: true, message: '请选择审核状态', trigger: 'change' }
        ]
      },
      imageArr: [],
      clothing: CLAZZ.clothing,
      newsType: CLAZZ.news,
      brand: CLAZZ.brand,
      style: CLAZZ.style,
      isAdd: true,
      skirtList: [],
      skirtArr: [],
      lifting: null,
      loading: false,
      selection: [],
      status_top: '',
      nowSkirt: {},
      nowMember: {},
      showFooter: true,
      updateRow: null
    }
  },
  methods: {
    getList () {
      let searchData = {delflag: '0'}
      if (this.$refs['search']) {
        searchData = this.$refs['search'].search()
      }
      let params = {...searchData, page: this.page.pageNum, size: this.page.pageSize, orderby: this.lifting}
      this.axios.get('/placard/index', {params})
        .then(res => {
          if (res.data.status) {
            this.page.total = Number(res.data.data.count)
            this.news = res.data.data.list
            this.news.forEach(item => {
              item.clothingid = item.clothingid.split(',')
              if (item.endtime === '售完下架') {
                item.endtime = null
              }
            })
          }
        })
    },
    handleSizeChange (e) {
      this.page.pageSize = e
      this.getList()
    },
    handleCurrentChange (e) {
      this.page.pageNum = e
      this.getList()
    },
    orderByTime (lifting) {
      // console.log(...arguments)
      if (lifting.order === 'ascending') {
        this.lifting = lifting.prop + ' asc'
      } else {
        this.lifting = lifting.prop + ' desc'
      }
      this.getList()
    },

    beforeUpload (file) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.imageArr.push(ev.currentTarget.result)
        _self.detailRow.imgarr.push(ev.currentTarget.result)
      }
      reader.readAsDataURL(file)
      return false
    },
    delImage (index) {
      this.imageArr.splice(index, 1)
      this.detailRow.imgarr.splice(index, 1)
    },
    toAdd () {
      this.showDetail = true
      this.isAdd = true
      this.imageArr = []
      this.showFooter = true
      this.nowSkirt = {}
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
        // this.$refs['addForm'].clearValidate()
      })
    },
    toSub (status) {
      if (status !== undefined) {
        this.detailRow.auditstatus = status
      } else {
        this.detailRow.auditstatus = this.updateRow.auditstatus
      }
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            // 添加
            this.addSubmit('/placard/add')
          } else {
            // 修改
            this.addSubmit('/placard/edit')
          }
        } else {
          this.$message.error('请检查表单是否填写正确')
          return false
        }
      })
    },
    addSubmit (url) {
      let params = {}
      Object.keys(this.detailRow).forEach(key => {
        if (this.detailRow[key] instanceof Array) {
          params[key] = this.detailRow[key].join(',')
        } else {
          params[key] = this.detailRow[key]
        }
      })
      params.imgarr = this.imageArr
      if (!params.endtime) {
        params.endtime = '售完下架'
      }
      this.axios.post(url, this.qs.stringify(params))
        .then(res => {
          if (res.data.status === 1) {
            this.$message.success(res.data.msg)
            this.getList()
            this.showDetail = false
          }
        })
    },

    toUpdate (row) {
      this.showDetail = true
      this.isAdd = false
      this.nowSkirt = {name: row.name}
      this.showFooter = (row.auditstatus === '4')
      this.updateRow = row
      this.$nextTick(() => {
        Object.keys(this.detailRow).forEach(key => {
          this.detailRow[key] = row[key]
        })
        this.imageArr = []
        this.detailRow.imgarr = []
        Object.keys(row).forEach(key => {
          if (key.indexOf('img') === 0 && row[key]) {
            this.imageArr.push(row[key])
            this.detailRow.imgarr.push(row[key])
          }
        })
        this.$refs['addForm'].clearValidate()
      })
    },
    toDelete (id, memberId) {
      deletePrompt({url: '/placard/delete', id, memberId}, res => {
        if (res.data.status === 1) {
          this.getList()
          this.$message.success(res.data.msg)
        }
      })
    },

    skirtChange (row) {
      this.nowSkirt = row
      this.detailRow.skirtid = row.id
      Object.keys(this.detailRow).forEach(key => {
        if (key !== 'id' && row[key] !== undefined) {
          this.detailRow[key] = row[key]
        }
        if (key === 'clothingid') {
          this.detailRow[key] = row[key].split(',')
        }
      })
    },
    memberChange (row) {
      this.nowMember = row
      this.detailRow.memberid = row.id
    },

    toExport () {
      this.loading = true
      let searchData = this.$refs['search'].search()
      toExport('/Placard/excelindex', searchData, '资讯', () => {
        this.loading = false
      })
    },

    toGetComment (id) {
      this.$refs['comment'].getList({type: '1', parid: id})
    },

    selectChange (selection) {
      this.selection = selection
    },
    review (type) {
      if (this.selection.length === 0) {
        this.$message.warning('请先选择要操作的对象')
      }
      let keys = ['id', 'skirtid', 'memberid', 'strattime', 'endtime', 'name', 'typeid']
      let tempArr = []
      this.selection.forEach(item => {
        let temp = {}
        keys.forEach(key => {
          temp[key] = item[key]
        })
        temp.starttime = temp.strattime
        delete temp.strattime
        tempArr.push(temp)
      })
      if (type === 3) {
        this.$prompt('请输入驳回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.toReview(tempArr, type, value)
        })
      } else {
        this.$confirm('确认批量审核通过吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.toReview(tempArr, type)
        })
      }
    },
    toReview (data, type, rejectcontent) {
      let params = {
        data,
        auditstatus: type
      }
      if (rejectcontent) {
        params.rejectcontent = rejectcontent
      }
      this.axios.post('/Placard/examine', this.qs.stringify(params))
        .then(res => {
          if (res.data.status === 1) {
            this.$message.success(res.data.msg)
            this.getList()
          }
        })
    },

    toPass (row, type) {
      let temp = {
        id: '',
        skirtid: '',
        memberid: '',
        strattime: '',
        endtime: '',
        name: '',
        typeid: ''
      }
      Object.keys(temp).forEach(key => {
        temp[key] = row[key]
      })
      if (type) {
        // 通过
        this.$confirm('确定通过审核吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.toReview([temp], 1)
        })
      } else {
        // 不通过
        this.$prompt('请输入驳回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          this.toReview([temp], 3, value)
        })
      }
    },

    toSelectSkirt () {
      this.$refs['selectList'].toShow()
    },
    toSelectMember () {
      this.$refs['selectMember'].toShow()
    },
    selectable (row, index) {
      return (row.delflag === '0' && row.auditstatus === '2')
    }
  },
  components: {
    comment,
    selectList
  },
  created () {
    this.getList()
  }
}
</script>

<style scoped>
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 30%;
  }
  .form .el-form-item{
    margin-right: 24px;
  }
  .avatar-uploader{
    display: inline-block;
    overflow: hidden;
  }
  .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .img-box{
    display: inline-block;
    position: relative;
  }
  .img-box i{
    position: absolute;
    top: 10px;
    right: 10px;
  }
  .avatar {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    border-radius: 6px;
    overflow: hidden;
  }
  .option-slot{
    display: flex;
    width: 100%;
    justify-content: center;
  }
  .option-slot .name2{
    font-size: 10px;
    color: #666;
    flex-grow: 0;
  }
  .option-slot .name1{
    flex-grow: 1;
    font-size: 13px;
  }
  .el-select-dropdown__item{
    height: auto;
  }
</style>
